package cn.jbolt.core.api;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.jfinal.kit.Okv;

/**
 * JBolt平台API 日志拦截器使用工具类
 *
 * @ClassName: JBoltApiLogKit
 * @author: JFinal学院-小木 QQ：909854136
 * @date: 2020年4月1日
 */
public class JBoltApiLogKit{
	/**
	 * 针对JwtParseResut的ThreadLocal
	 */
	private static final TransmittableThreadLocal<Okv> apiLogInfoTL = new TransmittableThreadLocal<Okv>();

	public static void init(Okv apiLogInfo) {
		if(apiLogInfo==null){
			throw new RuntimeException("JBoltApiLogKit init 参数不能为null");
		}
		apiLogInfoTL.set(apiLogInfo);
	}

	/**
	 * 设置BeforeValue 操作更新前的值
	 * @param beforeValue
	 */
	public static void setBeforeValue(Object beforeValue){
		set("before",beforeValue);
	}

	/**
	 * 设置AfterValue 操作更新后的值
	 * @param afterValue
	 */
	public static void setAfterValue(Object afterValue){
		set("after",afterValue);
	}

	/**
	 * 获取Before值
	 * @return
	 * @param <T>
	 */
	public static <T> T getBeforeValue(){
		Okv data = get();
		if(data==null){
			throw new RuntimeException("JBoltApiLogKit init 未调用");
		}
		return data.getAs("before");
	}

	/**
	 * 获取After值
	 * @return
	 * @param <T>
	 */
	public static <T> T getAfterValue(){
		Okv data = get();
		if(data==null){
			throw new RuntimeException("JBoltApiLogKit init 未调用");
		}
		return data.getAs("after");
	}

	/**
	 * 获取Before值 转Long
	 * @return
	 */
	public static Long getBeforeValueToLong(){
		Okv data = get();
		if(data==null){
			throw new RuntimeException("JBoltApiLogKit init 未调用");
		}
		return Long.getLong(data.getStr("before"));
	}

	/**
	 * 获取After值 转Long
	 * @return
	 */
	public static Long getAfterValueToLong(){
		Okv data = get();
		if(data==null){
			throw new RuntimeException("JBoltApiLogKit init 未调用");
		}
		return Long.getLong(data.getStr("after"));
	}

	public static Okv get(){
		return apiLogInfoTL.get();
	}
	public static void set(String key,Object value) {
		if(key==null || key.trim().length()==0){
			throw new RuntimeException("JBoltApiLogKit set(key,value) key 不能为null");
		}
		Okv data = get();
		if(data==null){
			throw new RuntimeException("JBoltApiLogKit init 未调用");
		}
		data.set(key,value);
	}
	/**
	 * 清空threadLocal
	 */
	public static void clear() {
		apiLogInfoTL.remove();
	}

}
